//
//  HTPlaceholderTextView.swift
//  mySinaBlog
//
//  Created by whtapple on 4/2/16.
//  Copyright © 2016 whtapple. All rights reserved.
//

import UIKit

class HTPlaceholderTextView: UITextView {
    //外界设置占位文本字体
    var placefont: UIFont?{
        didSet{
            placeholderLabel.font = placefont
        }
    }
    // 外界设置占位文字属性
    var placeholderText: String?{
        didSet{
            placeholderLabel.text = placeholderText
        }
    }
    //重写 text
    override var text: String? {
        didSet{
            //有文字就隐藏文本
            placeholderLabel.hidden = self.hasText()
        }
    }
    //初始化后
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        prepareUI()
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK -准备 UI
    private func prepareUI(){
        addSubview(placeholderLabel)
//        delegate = self
        placeholderLabel.translatesAutoresizingMaskIntoConstraints = false
        //设置占位 label的约束
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Leading, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Leading, multiplier: 1.0, constant: 5))
        addConstraint(NSLayoutConstraint(item: placeholderLabel, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: self, attribute: NSLayoutAttribute.Top, multiplier: 1.0, constant: 8))
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textViewDidChange", name: UITextViewTextDidChangeNotification, object: self)
    }
//监听回调方法
    func textViewDidChange(){
        //有文字就隐藏文本
        placeholderLabel.hidden = self.hasText()
    }
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    //mark -懒加载占位文本
   lazy var placeholderLabel: UILabel = {
        //搞一个站位 label
        let label = UILabel()
        //设置占位 label属性
        label.textColor = UIColor.lightGrayColor()
        label.text = "分享新鲜事......"
        label.font = UIFont.systemFontOfSize(18)
        return label
    }()
}
////MARK -扩展用消息代替了
//extension HTPlaceholderTextView: UITextViewDelegate{
//    //监听 textview的改变，来判断是否隐藏占位 label
//    func textViewDidChange(textView: UITextView) {
//        placeholderLabel.hidden = textView.hasText()
//    }
//}